package cn.com.dstz.admin.action;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;

import cn.com.dstz.agent.config.MemberConfig;
import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.security.encoder.Md5PwdEncoder;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.DateUtils;
import cn.com.dstz.utils.FillNameQuery;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;

/**
 * 用户管理
 * 2013-5-22 21:48 完成修复
 * 2013 -06-04 20:34 二次修复
 * @author 叶装装
 *
 */
public class MemberAct extends BaseAction{
	
	
	public void list( ){
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		Map< String, Object > valueMap = null;
		
		String sql = "select m.id as id, m.username as username,m.email as email, m.groupid as groupid, m.realname as realname, m.idcard as idcard, m.telephone as telephone, " +
				"m.qqnum as qqnum, m.regdate as regdate, m.expiredate as expiredate, m.mnumber as mnumber, m.onumber as onumber, m.aid as aid, m.status as status, g.name as groupname, a.name as agentname, ad.username as adminname  from dstzmember m left outer join dstzagent a on m.topaid = a.id left outer join dstzgroup g on m.groupid = g.id " +
				" left outer join dstzadmin ad on ad.id = m.adminid where 1=1" ;
		
		if( level > 0 ){
			
			MemberConfig config = new MemberConfig( admin, this.countManagerGroup( ) );
			sql += config.getSQL( );
			valueMap = config.getValueMap( );
			
			
			sql += " and a.status=:status";
			
			valueMap.put( "status", cn.com.dstz.admin.constants.Constants.ADMIN_STATUS_NORMAL );
			
		}


		Map< String, Type > aliasMap = DataBaseUtils.getAlias( new String[]{
				"id", "username", "email", "groupid", "realname", "idcard", "telephone",
				"qqnum","regdate","expiredate","mnumber","onumber","aid","status","groupname","agentname", "adminname"
		}, new Type[]{
				Hibernate.INTEGER, Hibernate.STRING, Hibernate.STRING, Hibernate.INTEGER, Hibernate.STRING, Hibernate.STRING, Hibernate.STRING, 
				Hibernate.STRING, Hibernate.STRING, Hibernate.STRING, Hibernate.STRING, Hibernate.STRING,  Hibernate.INTEGER, Hibernate.BYTE, Hibernate.STRING, Hibernate.STRING, Hibernate.STRING, Hibernate.STRING
		} );
		
		this.responseToJsonObject( this.paginationBySQL( sql, null, valueMap,  "m.regdate",  aliasMap )  );
		
		return;
		
	}
	
	public String toadd( ){
		setUserGroup( );
		return "add";
	}
	
	/**
	 * 添加用户
	 */
	public void add( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 0 ); // 验证
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		
		Date d = new Date( );
		String currentDate = DateUtils.formatDate( d, "yyyy-MM-dd" );
		
		if( StringUtils.isBlank( expiredate )){
			expiredate = DateUtils.formatDateByAddYear( d, 1 ); // 当前注册时间，+ 1年
		}
		
		Object topaid = admin.get( "topaid" );
		
		topaid = getTopaid( admin ); // 取得topaid

		int save = baseService.save( "dstzmember", DataBaseUtils.getData( new String[]{
				"username", "email", "password", "idcard", "telephone", "qqnum", 
				"regdate", "expiredate","mnumber","onumber",
				"groupid", "aid", "status", "topaid", "realname", "adminid"
				
		}, new Object[]{
				username, email, password, idcard, telephone, qqnum, currentDate , expiredate,mnumber,onumber,
				groupid,  admin.get( "topaid" ), getStatus( ),  topaid, realname, admin.get( "id" )
		} ), false );
		
		this.addLog( save, "member", 0, username );
		
		this.ajaxResponse( save > 0 ? 0 : -1 );
		return;
	}
	
	public String toedit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			this.alertMsg( null );
			return "edit";
		}
		
		
		setUserGroup( );
		
		String sql = "select * from dstzmember where id=:id";
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "id", id );
		Map< String, Object > data = baseService.queryForMap( sql, valueMap );
		getRequest( ).setAttribute( "data", data );
		
		return "edit";
	}
	
	public void edit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 1 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		Map< String, Object > updateData = getUpdateData( );
		
		int update = baseService.update( "dstzmember", updateData, DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		this.addLog( update, "member", 1, "ID：" + id );
		
		this.ajaxResponse( update > 0 ? 0 : -1 );
		
		return;
		
	}
	
	public void delete( ){
		
		String ids = getParameter( "ids" );
		
		if( ids != null ){
			String [] splitIds = StringUtils.split( ids, "," );
			
			if( splitIds != null && splitIds.length > 0 ){
				List< String > updateSqlList = new ArrayList< String >( );
				
				Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
				int level = ActionUtils.getAdminLevel( admin );
				
				for( String id : splitIds ){
					if( StringUtils.isNotBlank( id )){
						
						if( level == 0 ){
							updateSqlList.add( "delete from dstzmember where id =" + id);
						}else{
							updateSqlList.add( "update dstzmember set status = " + cn.com.dstz.admin.constants.Constants.ADMIN_STATUS_DISABLED + " where id =" + id + " and adminid=" + admin.get( "id" ));
						}
					}
				}
				
				int del = baseService.saveOrUpdateBatch( updateSqlList );
				this.addLog( del, "member", 2, ids );
			}
		}
	}
	
	private Map< String, Object > getUpdateData( ){
		Map< String, Object > updateData = new HashMap< String, Object >( );
		
		updateData.put( "username", username );
		updateData.put( "email", email );
		updateData.put( "idcard", idcard );
		updateData.put( "telephone", telephone );
		updateData.put( "qqnum", qqnum );
		updateData.put( "groupid", groupid );
		updateData.put( "realname", realname );
		updateData.put( "onumber", onumber );
		updateData.put( "mnumber", mnumber );
		updateData.put( "status", getStatus() );
		
		if( StringUtils.isNotBlank( password )){
			updateData.put( "password", password );
		}
		
		if( StringUtils.isNotBlank( expiredate )){
			updateData.put( "expiredate", expiredate ); // 设置过期时间
		}
		return updateData;
	}
	
	private int validSaveOrUpdate( int saveOrUpdate ){
		
		// 等于2 表示是 转到编辑页面或者删除
		if( saveOrUpdate == 2 ){
			if( id == null || id == 0 ){
				return 1;
			}
			return 0;
		}
		
		
		if( ValidUtils.validLength( username, 3, 20 )){
			return 1;
		}
		
		if( saveOrUpdate == 0 ){
			if( StringUtils.isBlank( password )){
				return 2;
			}
		}
		
		if( ValidUtils.validLengthCanEmpty( email,  40 )){
			return 3;
		}
		
		if( ValidUtils.validLengthCanEmpty( realname,  20 )){
			return 4;
		}
		
		if( ValidUtils.validLengthCanEmpty( idcard,  18 )){
			return 5;
		}
		
		if( ValidUtils.validLengthCanEmpty( telephone,  11 )){
			return 6;
		}
		
		if( ValidUtils.validLengthCanEmpty( qqnum,  15 )){
			return 7;
		}
		
		if( groupid == null || groupid == 0 ){
			return 8;
		}
		
		int count = 0;
		if( saveOrUpdate == 0 ){
			count = dbValid( );
		}else{
			if(! StringUtils.equals( oldusername, username )){
				count = dbValid( );
			}
		}
		if( count > 0 ){
			return 9;
		}
		
		return 0;
		
	}
	
	private int dbValid( ){
		return baseService.countBySQL( "select count(*) as a from dstzmember where username=:username", DataBaseUtils.getData( new String[]{
				"username"
		}, new Object[]{
				username
		} ) );
	}
	
	private Object getTopaid(  Map< String, Object > admin ){
		String sql = "select * from dstzagent where id=:id";
		Object topaid = admin.get( "topaid" );
		
		Map< String, Object > intermediate = baseService.queryForMap( sql, FillNameQuery.fillValue( sql, topaid ) );
		
		if( intermediate == null || intermediate.isEmpty( ) ){
			return topaid;
		}
		Object id = intermediate.get( "id" );
		
		Integer groupid = ( Integer ) admin.get( "groupid" );
		if( groupid != 2 ){
			Object faid = intermediate.get( "faid" );
			if( faid != null && ( Integer ) faid != 0 ){
				return intermediate.get( "faid" );
			}
		}
		
		return id;
	}
	
	private void setUserGroup( ){
		
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "ismanager", 0 );
		
		String sql = "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid and t.ismanager=:ismanager ";
		
		List< Map< String, Object >> groupList = baseService.queryForListByAll( sql, valueMap );
		
		getRequest( ).setAttribute( "groupList", groupList );
	}
	
	public void showDetailMember() throws UnsupportedEncodingException{
		String username = this.getParameter("username");
		
		//post请求发送
		if(StringUtils.isBlank(username))
			return ;
		else
			username = decodeString(username,"GBK");
		String sql = "SELECT m.username AS username ,m.status as status,m.email AS email ,m.realname AS realname ,m.telephone AS telephone ,m.qqnum AS qqnum ,m.regdate AS regdate ,g.name as groupname,m.expiredate AS expiredate, agent.name as agentname, admin.name AS adminname,admin.qqnum AS adminqq ";
		sql+=" FROM dstzmember m  LEFT outer JOIN dstzagent agent ON m.aid=agent.id  LEFT  outer JOIN dstzadmin admin  ON m.adminid=admin.id left outer join dstzgroup g on m.groupid = g.id WHERE m.username='"+username+"'"; 
			Map<String,Object> valueMap = baseService.getData(sql);
			String status = String.valueOf(valueMap.get("status"));
			String groupname = String.valueOf(valueMap.get("groupname"));
			String telephone = String.valueOf(valueMap.get("telephone"));
			if(StringUtils.isNotEmpty(status)){
				status = status.equals("1")?"正常":"过期";
			}
			if(StringUtils.isBlank(groupname)){
				groupname = "";
			}
			if(StringUtils.isNotEmpty(telephone)){
				if(telephone.length()<4){
					return ;
				}else if(telephone.length()<8){
					telephone = StringUtils.substring(telephone, 0, 3)+"****";
				}else {
					telephone = StringUtils.substring(telephone, 0, 3)+"****"+StringUtils.substring(telephone, 7, telephone.length());
				}
				
			}
			valueMap.put("status",status );
			valueMap.put("groupname",groupname );
			valueMap.put("telephone",telephone );
			this.responseToJsonObject(valueMap);
	}
	
	private Integer id;
	
	private String username;
	private String oldusername;
	
	private String email;
	private String password;
	private String realname;
	private String idcard;
	private String telephone;
	private String qqnum;
	private String onumber;
	private String mnumber;
	private Integer groupid;
	
	private Integer status;
	
	private String expiredate;
	
	
	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		this.id = id;
	}

	public String getUsername( ) {
		return username;
	}

	public void setUsername( String username ) {
		if( StringUtils.isNotBlank( username )){
			username = decode( username );
		}
		this.username = username;
	}

	public String getEmail( ) {
		return email;
	}

	public void setEmail( String email ) {
		if( StringUtils.isNotBlank( email )){
			email = decode( email );
		}
		this.email = email;
	}

	public String getPassword( ) {
		return password;
	}

	public void setPassword( String password ) {
		if( StringUtils.isNotBlank( password )){
			password =	pwdEncoder.md5( password );
		}
		this.password = password;
	}

	public String getRealname( ) {
		return realname;
	}

	public void setRealname( String realname ) {
		if( StringUtils.isNotBlank( realname )){
			realname = decode( realname );
		}
		this.realname = realname;
	}

	public String getIdcard( ) {
		return idcard;
	}

	public void setIdcard( String idcard ) {
		this.idcard = idcard;
	}

	public String getTelephone( ) {
		return telephone;
	}

	public void setTelephone( String telephone ) {
		this.telephone = telephone;
	}

	public String getQqnum( ) {
		return qqnum;
	}

	public void setQqnum( String qqnum ) {
		this.qqnum = qqnum;
	}

	public Integer getStatus( ) {
		if( status == null ){
			status = 0;
		}
		return status;
	}

	public void setStatus( Integer status ) {
		this.status = status;
	}
	

	public String getOldusername( ) {
		return oldusername;
	}

	public void setOldusername( String oldusername ) {
		if( StringUtils.isNotBlank( oldusername )){
			oldusername = decode( oldusername );
		}
		this.oldusername = oldusername;
	}
	
	

	public String getExpiredate( ) {
		return expiredate;
	}

	public void setExpiredate( String expiredate ) {
		this.expiredate = expiredate;
	}

	public Md5PwdEncoder getPwdEncoder( ) {
		return pwdEncoder;
	}

	public void setPwdEncoder( Md5PwdEncoder pwdEncoder ) {
		this.pwdEncoder = pwdEncoder;
	}


	public Integer getGroupid( ) {
		return groupid;
	}

	public void setGroupid( Integer groupid ) {
		this.groupid = groupid;
	}


	private Md5PwdEncoder pwdEncoder;
	
	private static final long serialVersionUID = 1L;
	
	
	public static void main( String [ ] args ) {
		
		Md5PwdEncoder pwdEncoder = new Md5PwdEncoder( );
		System.out.println( pwdEncoder.md5( "admins" ) );
		
	}

	public String getOnumber() {
		return onumber;
	}

	public void setOnumber(String onumber) {
		this.onumber = onumber;
	}

	public String getMnumber() {
		return mnumber;
	}

	public void setMnumber(String mnumber) {
		this.mnumber = mnumber;
	}
	
}

